import { ref } from 'vue'
import _ from 'lodash-es'
import Api from '@/libs/api'
import { useI18n } from 'vue-i18n'
import type { Ref } from 'vue'
import type { GoodsEditForm } from './types'

export const useGoodsSkuBatch = (editForm: Ref<GoodsEditForm>, skuSelects: Ref<any[]>) => {
	const { t } = useI18n()

	const checkBatchSel = () => {
		if (skuSelects.value.length === 0) {
			Api.notify(t('通知.请选择至少一个sku'))
			return false
		} else {
			return true
		}
	}

	const batchQuantitySet = (dataIndex: string) => {
		if (!checkBatchSel()) {
			return false
		}
		const reg = /^\d*$/
		const value = (
			document.querySelector(`[ref="batchQuantitySet-${dataIndex}"]`) as HTMLInputElement
		)?.value
		console.log('batchQuantitySet value:', value, 'dataIndex:', dataIndex)
		if (!reg.test(value)) {
			Api.notify(t('通知.请输入正整数'))
			return false
		}
		editForm.value.skus.forEach((sku, key) => {
			if (_.includes(skuSelects.value, sku.key)) {
				sku[dataIndex] = value
			}
		})
	}

	const quantityInput = (e: Event) => {
		const value = (e.target as HTMLInputElement).value
		if (value === '') (e.target as HTMLInputElement).value = '0'
	}

	const batchPriceSet = (dataIndex: string) => {
		if (!checkBatchSel()) {
			return false
		}
		const reg = /^\d+(\.\d{1,2})?$/
		const valueStr = (
			document.querySelector(`[ref="batchPriceSet-${dataIndex}"]`) as HTMLInputElement
		)?.value
		const value = parseFloat(valueStr)
		if (!reg.test(valueStr)) {
			Api.notify(t('通知.请输入正数金额格式'))
			return false
		}
		editForm.value.skus.forEach((sku, key) => {
			if (_.includes(skuSelects.value, sku.key)) {
				sku[dataIndex] = value.toFixed(2)
			}
		})
	}

	const priceInput = (e: Event) => {
		const value = (e.target as HTMLInputElement).value
		if (value === '') (e.target as HTMLInputElement).value = '0'
	}

	const batchCoverSet = (dataIndex: string) => {
		if (checkBatchSel()) {
			// 这个函数应该在 SkuAttributes.vue 组件中实现
			// (document.querySelector('[ref="skuBatchPriceChange"]') as HTMLInputElement)?.click()
			// 通过事件或回调来处理批量封面设置
			console.log('batchCoverSet called for:', dataIndex)
		}
	}

	const batchChangeCover = (e: Event) => {
		const file = (e.target as HTMLInputElement).files?.[0]
		if (file) {
			const coverSrc = URL.createObjectURL(file)
			editForm.value.skus.forEach((sku, key) => {
				if (_.includes(skuSelects.value, sku.key)) {
					sku.cover = coverSrc
				}
			})
		}
	}

	const batchCoverDelete = (dataIndex: string) => {
		if (checkBatchSel()) {
			editForm.value.skus.forEach((sku, key) => {
				if (_.includes(skuSelects.value, sku.key)) {
					sku.cover = null
				}
			})
		}
	}

	return {
		checkBatchSel,
		batchQuantitySet,
		quantityInput,
		batchPriceSet,
		priceInput,
		batchCoverSet,
		batchChangeCover,
		batchCoverDelete
	}
}
